<template>
  <div class="cart">
    <nut-navbar fixed>
      <template #left>
        <div>购物车</div>
      </template>
      <template #right>
        <div v-if="!deleteStatus" @click="switchDeleteStatus(true)">管理</div>
        <div v-if="deleteStatus" @click="switchDeleteStatus(false)">取消</div>
      </template>
    </nut-navbar>
    <nut-pull-refresh v-model="refreshStatus" @refresh="refreshData">
      <nut-empty v-if="$store.state.cartModule.cartList.length == 0" description="  "></nut-empty>
      <ul>
        <li
          v-for="(cart, cartIndex) in $store.state.cartModule.cartList"
          :key="cartIndex"
        >
          <div class="check">
            <nut-checkbox
              :disabled="!cart.stockEnough || !cart.exists"
              @change="(selected) => selectCart(cart.id, selected)"
              v-model="cart.selected"
            ></nut-checkbox>
          </div>
          <img src="@/assets/product/mi14.jpg" alt="" />
          <div class="info">
            <div class="sku">
              <nut-ellipsis
                class="title"
                :content="cart.skuInfo.title"
                direction="end"
                rows="2"
              ></nut-ellipsis>
              <span class="attr">
                <div>
                  <span
                    v-for="(skuAttr, skuAttrIndex) in cart.skuInfo.skuAttrList"
                    :key="skuAttrIndex"
                  >
                    {{ skuAttr.attrValue }}
                  </span>
                </div>
                <span class="error" v-if="!cart.stockEnough">库存不足</span>
                <span class="error" v-if="!cart.exists">商品已下架</span>
              </span>
            </div>
            <div class="priceBox">
              <nut-price
                :price="cart.skuInfo.price"
                size="normal"
                position="after"
                symbol="元"
              />
              <nut-input-number
                min="1"
                :max="cart.skuInfo.stockNum - cart.skuInfo.lockedNum"
                v-model="cart.quantity"
                :disabled="!cart.exists"
                :readonly="!cart.exists"
                @change="(quantity) => changeQuantity(cart.id, quantity)"
              />
            </div>
          </div>
        </li>
      </ul>
    </nut-pull-refresh>

    <div class="fixedTotal">
      <div class="total">
        <div class="info">
          <div class="check">
            <nut-checkbox
              v-model="allSelected"
              @click="selectAllCart"
            ></nut-checkbox>
          </div>
          <div class="money">
            <span class="num"
              >已选<span>{{
                $store.getters["cartModule/selectedProductQuantity"]
              }}</span
              >件，合计</span
            >
            <nut-price
              :price="$store.getters['cartModule/selectedProductTotalAmount']"
              size="normal"
              position="after"
              symbol="元"
            />
          </div>
        </div>
        <div class="btn">
          <nut-button
            v-if="!deleteStatus"
            :loading="loadingStatus.confirm"
            :disabled="$store.getters['cartModule/selectedProductQuantity'] &lt;= 0 || loadingStatus.confirm"
            type="primary"
            @click="jumpToConfirmOrder"
            >去结算</nut-button
          >
          <nut-button
            v-if="deleteStatus"
            :loading="loadingStatus.delete"
            :disabled="$store.getters['cartModule/selectedProductQuantity'] &lt;= 0"
            type="primary"
            @click="deleteCart"
            >删除</nut-button
          >
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import cart from "@/store/modules/cart";
import userUtils from "@/utils/userUtils";
import { getCurrentInstance, onMounted, reactive, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
const route = useRoute();
const router = useRouter();
const { proxy } = getCurrentInstance();

// 下拉刷新
const refreshStatus = ref(false);
const refreshData = () => {
  proxy.$cartUtils.refreshCartList();
  refreshStatus.value = false;
  allSelected.value = proxy.$cartUtils.isAllSelected();
};

// 按钮状态
const loadingStatus = reactive({
  confirm: false,
  delete: false,
});

// 删除状态
const deleteStatus = ref(false);
const switchDeleteStatus = (status) => {
  deleteStatus.value = status;
};
// 删除购物车
const deleteCart = () => {
  loadingStatus.delete = true;
  var cartList = proxy.$cartUtils.getSelectedCartList();
  var cartIds = [];
  cartList.forEach((cart) => {
    cartIds.push(cart.id);
  });
  proxy.$cartApi.cart
    .deleteCart(cartIds)
    .then((res) => {
      proxy.$cartUtils.refreshCartList();
      loadingStatus.delete = false;
    })
    .catch((error) => {
      loadingStatus.delete = false;
    });
};

// 是否全部选中
const allSelected = ref(false);

// 选择购物车
const selectCart = (id, selected) => {
  proxy.$cartUtils.selectCart(id, selected);
  allSelected.value = proxy.$cartUtils.isAllSelected();
};

// 全部选中或取消
const selectAllCart = () => {
  proxy.$cartUtils.selectAllCart(allSelected.value);
};

// 数量变化
const changeQuantity = (id, quantity) => {
  proxy.$cartApi.cart.updateCart(id, quantity).then((res) => {
    proxy.$cartUtils.refreshCartList();
  });
};

// 去结算
const jumpToConfirmOrder = () => {
  var cartList = proxy.$cartUtils.getSelectedCartList();
  var skuQuantityList = [];
  var cartIds = [];
  cartList.forEach((cart) => {
    skuQuantityList.push({
      skuId: cart.skuId,
      quantity: cart.quantity,
    });
    cartIds.push(cart.id);
  });
  loadingStatus.confirm = true;
  // 库存检查
  proxy.$orderApi.order
    .stockCheck(cartList)
    .then((res) => {
      loadingStatus.confirm = false;
      if (res.data.length == 0) {
        router.push({
          path: "/order/confirm",
          state: {
            cartMode: true,
            cartIds: cartIds,
            addressId: null,
            skuQuantityList: skuQuantityList,
          },
        });
      } else {
        proxy.$showToast.fail("当前商品库存不足");
      }
    })
    .catch((error) => {
      loadingStatus.confirm = false;
    });
};

// 页面加载完成
onMounted(() => {
  proxy.$cartUtils.refreshCartList();
  allSelected.value = proxy.$cartUtils.isAllSelected();
});
</script>

<style lang="less" scoped>
.cart {
  ul {
    margin: 0px 0px 65px 0px;
    padding: 5px 10px 0px 10px;
    li {
      display: flex;
      height: 100px;
      margin-bottom: 5px;
      background: #fff;
      padding: 10px 0px;
      border-radius: 5px;
      img {
        width: 80px;
        height: 80px;
        margin: 10px 5px 0px 5px;
        border-radius: 5px;
      }
      .check {
        width: 30px;
        display: flex;
        justify-content: center;
        margin: 0px -20px 0px 20px;
      }
      .info {
        flex: 1;
        padding: 5px;
        margin: 0px 5px 0px 0px;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        .sku {
          .title {
            margin-bottom: 5px;
            font-size: 12px;
          }
          .attr {
            font-size: 12px;
            display: flex;
            justify-content: space-between;
            .error {
              color: #fa2c19;
            }
          }
        }
        .priceBox {
          display: flex;
          justify-content: space-between;
          align-items: center;
        }
      }
    }
  }
  .fixedTotal {
    background: #fff;
    width: 100%;
    position: fixed;
    bottom: 50px;
    .total {
      height: 60px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0px 10px;
      .info {
        display: flex;
        justify-content: flex-start;
        padding: 0px 0px 0px 10px;
        .check {
          display: flex;
          width: 30px;
        }
        .money {
          display: flex;
          align-items: center;
          .num {
            margin-right: 5px;
            span {
              margin: 0px 5px;
            }
          }
        }
      }
      .btn {
        :deep(.nut-button) {
          display: flex;
          font-size: 13px;
          align-items: center;
        }
      }
    }
  }
}
</style>